package com.bci.internal.engine.bcibpmengine.service.impl;


import com.bci.internal.engine.bcibpmengine.service.ActivitiBaseService;
import com.bci.internal.engine.bcibpmengine.utils.ConstantUtils;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author jzwu
 * @since 2021/4/5 0005
 */
@Slf4j
@Service
public class ActivitiBaseServiceImpl implements ActivitiBaseService {

    @Resource
    private RepositoryService repositoryService;


    @Override
    public String uploadBpmFile(MultipartFile multipartFile) {
        Assert.notNull(multipartFile, "上传流程部署文件不能为空！");
        String fileName = multipartFile.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        /* 上传后的路径 */
        String filePath = ConstantUtils.BPMN_PathMapping;
        /* 本地路径格式转上传路径格式 */
        filePath = filePath.replace("\\", "/");
        filePath = filePath.replace("file:", "");
        /* 新文件名 */
        fileName = UUID.randomUUID() + suffixName;
        File file = new File(filePath + fileName);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        try {
            multipartFile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage());
            throw new IllegalArgumentException("上传部署文件异常！");
        }
        return fileName;
    }

    @Override
    public String transationDeploymentByString(String stringBPMN) {
        Deployment deployment = repositoryService.createDeployment()
                .addString("CreateWithBPMNJS.bpmn", stringBPMN)
                .name("自定义流程")
                .deploy();
        return deployment.getId();
    }
}